package com.gitee.wsl.coroutines.executor.runnable

import com.gitee.wsl.concurrent.api.RunnableWithResult
import kotlinx.atomicfu.AtomicLong

/**
 * CountedRunnable is an open class that implements the Runnable interface.
 * It is used to execute a task and keep track of the number of active tasks using an AtomicLong counter.
 * The class takes an AtomicLong counter and a parent task as constructor parameters.
 *
 * @param count The AtomicLong counter to keep track of the number of active tasks.
 * @param parentTask The parent task to be executed.
 */
open class CountedRunnableWithResult<T>(
    protected val count: AtomicLong,
    protected val parentTask: RunnableWithResult<T>
) : RunnableWithResult<T> {
    override fun run():T {
        count.incrementAndGet()
        try {
            return parentTask.run()
        } finally {
            count.decrementAndGet()
        }
    }
}